package com.bridge.applets.config;

import com.bridge.common.enums.RSEnum;
import com.bridge.common.exception.BusException;
import com.bridge.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {
            BusException.class})
    public R handleRuntimeException(BusException ex) {
        log.error("业务日志打印:", ex);
        return R.fail(ex.getStatus(), ex.getMessage());
    }

    @ExceptionHandler(value = {
            Exception.class})
    public R handleRuntimeException(Exception ex) {
        log.error("错误日志打印:", ex);
        return R.fail();
    }

    @ExceptionHandler(value = {
            MyBatisSystemException.class})
    public R handleRuntimeException(MyBatisSystemException ex) {
        log.error("业务日志打印:", ex);
        if (ex.getCause() != null && ex.getCause().getCause() != null) {
            return R.fail(RSEnum.resolve(ex.getCause().getCause().getMessage()));
        }
        return R.fail();
    }



    @ExceptionHandler(Throwable.class)
    public R handleThrowable(Throwable e, HttpServletRequest request) {
        log.error("URL:{} ,系统异常: ",request.getRequestURI(), e);
        return R.fail(RSEnum.SYSTEM_ERROR.status(),e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public R exceptionHandler(BindException e, HttpServletRequest request) {
        String failMsg = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("URL:{} ,绑定异常:{} ", request.getRequestURI(),failMsg);
        return R.fail(RSEnum.SYSTEM_ERROR.status(),failMsg);
    }

}
